package com.ljs.module.service;

import com.ljs.module.common.DataBean;
import com.ljs.module.common.TypeEnum;
import com.ljs.module.util.TemplateUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


public class ScriptMethods {

    private Map<String, Object> data = new HashMap<>();

    public ScriptMethods(Map<String, Object> data) {
        this.data = data;
    }

    public DataBean createDir(String path) {
        try {
            File file = new File(path);
            file.mkdirs();
            return DataBean.success();
        } catch (Exception e) {
            return DataBean.fail("创建路径" + path + "失败;" + e.getMessage());
        }
    }

    public DataBean createFile(String path, String name) {
        try {
            File file = new File(path, name);
            if (file.exists()) {
                return DataBean.success(file);
            }
            file.createNewFile();
            return DataBean.success(file);
        } catch (Exception e) {
            return DataBean.fail("创建路径" + path + "失败; " + e.getMessage());
        }
    }

    public DataBean createFile(String path, String name, String module) {
        try {
            return createFileAppend(path, name, module, false);
        } catch (Exception e) {
            return DataBean.fail("创建路径" + path + "失败;" + e.getMessage());
        }
    }

    public DataBean createFileAppend(String path, String name, String module, Boolean isAppend) {
        FileOutputStream fos = null;
        try {
            createDir(path);
            DataBean<File> fileBean = createFile(path, name);
            if (fileBean.getReasonCode() != 2000) {
                return fileBean;
            }
            File file = fileBean.getData();
            fos = new FileOutputStream(file, isAppend);
            String render = TemplateUtil.render(TypeEnum.CUSTOM_TEMPLATE.getTemplate() + File.separator + module + ".js", data);
            fos.write(render.getBytes(StandardCharsets.UTF_8));
            return DataBean.success();
        } catch (Exception e) {
            return DataBean.fail("创建路径" + path + "失败;" + e.getMessage());
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
